package net.keebook.webapp.util;

import java.text.MessageFormat;
import java.util.TimeZone;

import net.keebook.webapp.dao.AccountConfirmationDao;
import net.keebook.webapp.dao.SettingDao;
import net.keebook.webapp.entity.AccountConfirmation;
import net.keebook.webapp.entity.User;

public class AccountConfirmationMail {
	public static void send(User user, AccountConfirmationDao accountConfirmationDao, SettingDao settingDao) {
		// Invalidate old account confirmation requests for this user
		accountConfirmationDao.deleteAllUserConfirmations(user.getId());
		
		// Create new account confirmation request
		AccountConfirmation confirmation = new AccountConfirmation();
		confirmation.setUser(user);
		confirmation.setCreationDate(DateUtil.getUtcTimestamp(TimeZone.getTimeZone(settingDao.get(SettingId.SYSTEM_TIMEZONE).getValue())));
		accountConfirmationDao.store(confirmation);
		
		String url = settingDao.get(SettingId.PUBLIC_URL).getValue() + "/services/confirm/" + confirmation.getExposableId();
		String message = MessageBundle.get().getString("mail.signupMail");
		message = MessageFormat.format(message, url);
		
		Mail mail = new Mail(
				settingDao.get(SettingId.SMTP_HOST).getValue(), 
				settingDao.get(SettingId.SMTP_PORT).getLong().intValue(),
				settingDao.get(SettingId.SMTP_AUTH).getBoolean(),
				settingDao.get(SettingId.SMTP_USERNAME).getValue(),
				settingDao.get(SettingId.SMTP_PASSWORD).getValue(),
				settingDao.get(SettingId.SMTP_ENABLE).getBoolean());
		try {
			mail.sendMail(
				settingDao.get(SettingId.SMTP_SENDER_ADDRESS).getValue(),
				"KeeBook",
				user.getEmail(),
				null,
				MessageBundle.get().getString("mail.signupMailSubject"),
				message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
